package edu.dayu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.dayu.enums.DictEnum;
import edu.dayu.mapper.BookingRuleMapper;
import edu.dayu.mapper.HospitalMapper;
import edu.dayu.model.hosp.BookingRule;
import edu.dayu.model.hosp.Hospital;
import edu.dayu.service.DictDubbo;
import edu.dayu.service.HospitalService;
import edu.dayu.vo.hosp.HospitalQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalMapper hospitalMapper;

    @Autowired
    private BookingRuleMapper bookingRuleMapper;

    @DubboReference
    private DictDubbo dictDubbo;


    @Override
    public void save(Map<String, Object> paramMap) {
        /**
         *  Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(paramMap),Hospital.class);
         * Map转换为Hospital对象时，预约规则bookingRule为一个对象属性，rule为一个数组属性，因此在转换时我们要重新对应的set方法，不然转换不会成功
         */
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Hospital.class);
        BookingRule bookingRule = JSONObject.parseObject(JSONObject.toJSONString(paramMap), BookingRule.class);
        Hospital targetHospital = hospitalMapper.selectOne(new QueryWrapper<Hospital>(new Hospital()).eq("hoscode",hospital.getHoscode()));
        if (null != targetHospital){
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            bookingRule.setUpdateTime(new Date());
            bookingRuleMapper.updateById(bookingRule);
            hospitalMapper.updateById(hospital);
        }else {
            //0：未上线 1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            bookingRuleMapper.insert(bookingRule);
            hospital.setBookingRuleId(bookingRule.getId());
            hospitalMapper.insert(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = new Hospital();
        hospital.setHoscode(hoscode);
        List<Hospital> hospitals = hospitalMapper.queryHospital(hospital);
        return  hospitals.get(0);
    }

    @Override
    public PageInfo<Hospital> selectPage(Integer page, Integer size, HospitalQueryVo hospitalQueryVo) {
        PageHelper.startPage(page,size);

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        List<Hospital> hospitalList = hospitalMapper.queryHospitalDesc(hospital);
        hospitalList.stream().forEach(item->{
            this.packHospital(item);
        });
        PageInfo<Hospital> pageInfo = new PageInfo<>(hospitalList);
        return pageInfo;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        if(status == 0 || status == 1) {
            Hospital hospital = hospitalMapper.selectById(id);
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalMapper.updateById(hospital);
        }
    }

    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital1 = new Hospital();
        hospital1.setId(new Long(id));
        List<Hospital> hospitals = hospitalMapper.queryHospital(hospital1);
        if (hospitals.size()>0){
            Hospital hospital = this.packHospital(hospitals.get(0));
            result.put("hospital", hospital);

            //单独处理更直观   需要多表
            result.put("bookingRule", hospital.getBookingRule());
            //不需要重复返回
            hospital.setBookingRule(null);
        }
        return result;
    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        Hospital hospital = new Hospital();
        hospital.setHosname(hosname);
        return hospitalMapper.queryHospital(hospital);
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.packHospital(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    /**
     * 封装数据
     * @param hospital
     * @return
     */
//    @SentinelResource(value = "packHospital" ,fallback = "fallback")
    private Hospital packHospital(Hospital hospital) {
        String hostypeString = dictDubbo.getNameByParentDictCodeAndValue(DictEnum.HOSTYPE.getDictCode(),hospital.getHostype());
        String provinceString = dictDubbo.getNameByParentDictCodeAndValue(null,hospital.getProvinceCode());
        String cityString = dictDubbo.getNameByParentDictCodeAndValue(null,hospital.getCityCode());
        String districtString = dictDubbo.getNameByParentDictCodeAndValue(null,hospital.getDistrictCode());

        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }

    private Hospital fallback(){
        return new Hospital();
    }
}
